package cn.qfei.qiyuesuo.service.impl;

import cn.qfei.qiyuesuo.api.*;
import cn.qfei.qiyuesuo.bo.*;
import cn.qfei.qiyuesuo.common.enums.ErrorCode;
import cn.qfei.qiyuesuo.common.until.QiyuesuoCallbackUtils;
import cn.qfei.qiyuesuo.service.QiyuesuoApiService;
import cn.qfei.qiyuesuo.vo.qiyuesuo.CallbackData;
import cn.qfei.qiyuesuo.vo.qiyuesuo.CallbackValidateResult;
import cn.qfei.qiyuesuo.vo.qiyuesuo.QysContractNoticeVo;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
public class QiyuesuoApiServiceImpl implements QiyuesuoApiService {

    @Value("${qiyuesuo.baseServiceUrl}")
    private String baseServiceUrl;
    @Value("${qiyuesuo.accessToken}")
    private String accessToken;
    @Value("${qiyuesuo.accessSecret}")
    private String accessSecret;
    @Value("${qiyuesuo.aesKey}")
    private String aesKey;
    @Value("${qiyuesuo.token}")
    private String token;

    @Value("${qiyuesuo.basePath}")
    private String basePath;
    private static String DE_FILE_TYPE = "docx";

    /**
     * 获取合同详情
     *
     * @param contractId
     * @return
     */
    public DetailContractBo getContractDetail(String contractId) {
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        QysResponse<DetailContractBo> response = aysClient.getContractDetail(contractId);
        if (response.getCode() == 0) {
            return response.getResult();
        }
        return null;
    }

    /**
     * 获取用户签约地址
     *
     * @param contractId
     * @return
     */
    public PresignurlBo getContractPresignurl(String contractId) {
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        QysResponse<PresignurlBo> response = aysClient.getContractPresignurl(contractId, null);
        if (response.getCode() == 0) {
            return response.getResult();
        }
        return null;
    }


//        public CompanysignsilentUrlBo getCompanysignsilentUrl(long contractId, String qfFileId) {
//                QiyuesuoClient aysClient=new QiyuesuoClient(baseServiceUrl,accessToken,accessSecret);
//                QysResponse<CompanysignsilentUrlBo> response=  aysClient.getCompanysignsilentUrl(company,null,adminMobile,authScope);
//                if (response.getCode()==0){
//                        return response.getResult();
//                }
//                return null;
//        }

    public String signContractBycompany(String contractId, String ourPartyName, String sealIds) {
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        QysResponse response = aysClient.signContractBycompany(sealIds, ourPartyName, contractId);
        if (response != null) {
            log.info("返回ma{},提示={}", response.getCode(), response.getMessage());


        }
        return response.getMessage();
    }

    @Override
    public CallbackValidateResult callbackValidateResult(CallbackData callbackData) {
        QiyuesuoCallbackUtils callbackUtils = new QiyuesuoCallbackUtils(aesKey, token);
        return callbackUtils.callbackValidateResult(callbackData);
    }

    @Override
    public QysContractNoticeVo getQysContractNoticeVo(String plainText) {
        if (StringUtils.isBlank(plainText)) {
            return null;
        }
        return JSON.parseObject(plainText, QysContractNoticeVo.class);
    }

    @Override
    public ErrorCode updatePreSignurl(QysContractNoticeVo vo) {
        return null;
    }

    @Override
    public FilePathBo getPathDowlaod(String contractId) {
        FilePathBo bo = new FilePathBo();

        bo.setFileName(getPathName());
        String filePath = basePath + bo.getFileName();
        bo.setFilePath(filePath);
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        QysResponse response = aysClient.getcontractFile(contractId, filePath);
        if (response.getCode() == 0) {
            return bo;
        }
        return null;
    }

    private String getPathName() {
        Random random = new Random();
        String name = random.nextInt(10000) + "a" + System.currentTimeMillis()
                + ".zip";
        return name;
    }

    public List<SealCustomparamListBo> getsealList(String ourPartyName) {
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        String status = "NORMAL";
        QysResponse<List<SealCustomparamListBo>> res = aysClient.getsealList(ourPartyName, status);
        return res.getResult();
    }

    @Override
    public String addContract(List<FileItemBo> fileItemBos, String contractName, String bizId, String tenantName) {
        String categoryName = "飞书合同集成测试";
        String subject = categoryName;
        boolean send = false;
        List<Long> documents = new ArrayList<>();
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        for (FileItemBo fileItemBo : fileItemBos) {
            Long documentId = addFile(fileItemBo, contractName);
            log.info("文件id={}",documentId);
            if (documentId != null) documents.add(documentId);
        }
        QysResponse<String> res = aysClient.contractCreate(categoryName, subject, send, bizId, tenantName, documents);
        return res.getResult();
    }

    private Long addFile(FileItemBo fileItemBo, String contractName) {
        String fileType = getFileType(fileItemBo.getFileName());
        QiyuesuoClient aysClient = new QiyuesuoClient(baseServiceUrl, accessToken, accessSecret);
        QysResponse<DocumentCreatebyfilesBo> res = aysClient.documentCreatebyfile(fileItemBo, contractName, fileType);
        if (res.getCode() == 0) {
            DocumentCreatebyfilesBo filesBo = res.getResult();
            if (filesBo != null && StringUtils.isNotBlank(filesBo.getDocumentId())) {
                return Long.valueOf(filesBo.getDocumentId());
            }
        }
        return null;
    }

    private String getFileType(String fileName) {
        log.info("");
        if (StringUtils.isBlank(fileName) || fileName.indexOf(".") == -1) {
            return DE_FILE_TYPE;
        }
        String[] strList = fileName.split("\\.");
        return strList[strList.length - 1];


    }

    public static void main(String[] args) {
        String fileName="20240401测试合同1.pdf";
        String[] strList = fileName.split("\\.");
         System.out.println(fileName.indexOf("."));
    }
}
